#include "CEnemySpawner.h"
#include "../CGame.h"
#include "../core/CDirect3D.h"
#include "../core/CCamera.h"
#include "../core/CRetroInput.h"
#include "CObjectManager.h"

#include <assert.h>

CEnemySpawner::CEnemySpawner(void)
{
}

CEnemySpawner::~CEnemySpawner(void)
{
}

void CEnemySpawner::Initialize()
{
	CBaseObject::Initialize();
}

void CEnemySpawner::Initialize(int posX, int posY, float depth, int collisionWidth, int collisionHeight, USHORT enemiesToSpawnFlags, float activateRange, float spawnRate, UINT maxSpawn, CBaseObject* pObjectForRange)
{
	assert(pObjectForRange != NULL && "cannot give a NULL object for the range check");
	assert(enemiesToSpawnFlags != 0 && "Spawner must have enemies to spawn");
	CBaseEnemy::Initialize(posX, posY, depth, collisionWidth, collisionHeight, NULL);

	m_lEnemiesToSpawn = enemiesToSpawnFlags;
	m_fActivateRange = activateRange;
	m_fSpawnRate = spawnRate;
	m_unMaxSpawn = maxSpawn;
	m_fSpawnTimer = 0.0f;
	m_unCurrentSpawn = 0;
	m_bActivated = false;
	m_pObjectForRange = pObjectForRange;
	m_pObjMan = CObjectManager::GetInstance();
}

void CEnemySpawner::Input(CRetroInput* pInput)
{
}

void CEnemySpawner::Update(float fDeltaTime)
{
	if(m_bActivated)
	{
		// spawn enemies
		m_fSpawnTimer += fDeltaTime;
		if(m_fSpawnTimer > m_fSpawnRate)
		{
			// ensure we have room to spawn
			if(m_unCurrentSpawn < m_unMaxSpawn)
			{
				// determin the type to spawn
				EnemyType typeToSpawn = (EnemyType)0;
				UINT numBits = sizeof(USHORT) * 8;

				UINT bit = 1 << (rand() % numBits);
				if(bit & m_lEnemiesToSpawn)
				{
					typeToSpawn = (EnemyType)bit;
					CBaseEnemy* pEnemy = m_pObjMan->CreateEnemy(m_vfPosition.x, m_vfPosition.y, typeToSpawn);
					pEnemy->SetSpawnOwner(this);
					m_unCurrentSpawn++;
					m_fSpawnTimer = 0.0f;
				}
			}

		}
	}
	else
	{
		// check range towards object
		POINT targetPos = ((CBaseObject*)m_pObjectForRange)->GetPosition();
		LONG dX = targetPos.x - m_vfPosition.x;
		LONG dY = targetPos.y - m_vfPosition.y;
		float squareDist = static_cast<float>((dX * dX) + (dY * dY));
		if(squareDist <= m_fActivateRange * m_fActivateRange)
		{
			m_bActivated = true;
		}
	}
}

void CEnemySpawner::Render(CDirect3D* pRender, CCamera* pCamera)
{
	const POINT& camPos = pCamera->GetCameraOffset();
	RECT drawBox;
	drawBox.left	=	m_vfCollisionBox.left	+ m_vfPosition.x - camPos.x;
	drawBox.top		=	m_vfCollisionBox.top	+ m_vfPosition.y - camPos.y;
	drawBox.right	=	m_vfCollisionBox.right	+ m_vfPosition.x - camPos.x;
	drawBox.bottom	=	m_vfCollisionBox.bottom	+ m_vfPosition.y - camPos.y;

	if(m_bActivated)
	{
		pRender->DrawRect(drawBox, 0, 255, 0);
	}
	else
	{
		pRender->DrawRect(drawBox, 0, 128, 0);
	}

}

void CEnemySpawner::Destroy()
{
}

bool CEnemySpawner::CheckCollision(IBaseObject* pObject)
{
	return false;
}
